<template>
  <div id="menu-select">
    <el-container>
      <el-header>
        <el-link :underline="false" @click="submit" type="success" size="small" icon="el-icon-circle-check"> 确定</el-link>
        <el-divider direction="vertical"></el-divider>
        <el-link :underline="false" @click="selectAll" type="primary" size="small" icon="el-icon-circle-plus-outline"> 全选</el-link>
        <el-divider direction="vertical"></el-divider>
        <el-link :underline="false" @click="clean" type="danger" size="small" icon="el-icon-delete"> 清空</el-link>
        <el-divider></el-divider>
      </el-header>
      <el-main style="height: 450px">
        <el-tree
          :data="menuData"
          show-checkbox
          default-expand-all
          node-key="id"
          ref="tree"
          check-strictly
          highlight-current
          :props="defaultProps">
        </el-tree>
      </el-main>
    </el-container>
  </div>
</template>

<script>
  export default {
    props: {
      button: {
        type: Object,
      },
      selectKeys:{
        type: String
      },
    },
    name: "menu-select",
    components: {},
    data() {
      return {
        menuData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        keys:[],
      }
    },
    watch: {
      button: {
        handler() {
          if (this.common.isNotEmpty(this.button)) {
            this.getMenuData()
          }
        },
        deep: true
      },
      selectKeys:{
        handler(val){
          if (this.common.isNotEmpty(val)){
            let ar = val.split(',')
            this.$refs.tree.setCheckedKeys(ar);
          }
        },
        deep:true
      }
    },
    methods: {
      clean(){
        this.$refs.tree.setCheckedKeys([]);
      },
      selectAll(){
        let allKeys = this.common.getFieldInTree({treeData:this.menuData})
        this.$refs.tree.setCheckedKeys(allKeys);
      },
      submit(){
        let keys = ''
        this.$refs.tree.getCheckedKeys().forEach(key=>{
          keys += key + ','
        })
        this.keys = keys.substring(0,keys.length-1)
        this.$emit('choseMenu',this.keys)
      },
      getMenuData() {
        console.log('请求菜单')
        this.common.request({
          url: this.button.target,
          param: {},
          permission: this.button.id,
          success: res => {
            if (res.code == 1) {
              this.$nextTick(()=>{
                this.menuData = $.extend(true, [], res.data.rows)
              })
            }
          }
        })
      },
    },
    mounted() {
        this.getMenuData()
    }
  }
</script>

<style scoped>

</style>
